Page({
  data: {
    isEnd: false,
    items: []
  },

  _id: 0,

  onLoad () {
    this._render();
  },

  onReachBottom () {
    this._render();
  },

  _render () {

    if (this.data.isEnd) {
      return;
    }

    wx.showLoading({
      title: '数据加载中'
    });

    this._getItems().then(({isEnd, data}) => {
      wx.hideLoading();
      // 优化数据的添加
      let items = this.data.items;
      let index = items.length++;
      let newObj = {};
      data.forEach(item => {
        newObj[`items[${index++}]`] = item;
      });
      if (isEnd) newObj.isEnd = isEnd;
      this.setData(newObj);
    });
  },

  /**
   * 模拟获取数据
   */
  _getItems () {
    let colors = ['#f37b1d', '#fbbd08', '#39b54a', '#fadbd9', '#39b54a', '#8799a3', '#a5673f', '#333333', '#666666', '#ffffff', '#e8f4d9', '#fde6d2', '#cce6ff', '#d2f1f0'];
    let data = [];
    // 每次加载数据长度
    let dataLen = 7;
    // 数据加载次数（模拟数据完结）
    let dataTimes = 3;
    for (let i = 0; i < dataLen; i++) {
      data.push({
        id: this._id++,
        height: Math.floor(Math.random() * 350 + 200),
        color: colors[Math.floor(Math.random() * colors.length)]
      });
    }
    return new Promise (resolve => {
      setTimeout(() => {
        resolve({
          isEnd: this._id >= dataLen * dataTimes,
          data
        });
      }, 250);
    });
  }
});
